package cn.kuick.match.test1;


public class Test1 {

	private int[] nums = new int[7];
	private char[] codes = new char[7];

	public Test1() {
		intNums();
		initMap();
	}

	private void intNums() {
		nums[0] = 1;
		nums[1] = 5;
		nums[2] = 10;
		nums[3] = 50;
		nums[4] = 100;
		nums[5] = 500;
		nums[6] = 1000;
	}

	private void initMap() {
		codes[0] = 'I';
		codes[1] = 'V';
		codes[2] = 'X';
		codes[3] = 'L';
		codes[4] = 'C';
		codes[5] = 'D';
		codes[6] = 'M';
	}

	private int charToNum(char ch) {
		for (int i = codes.length - 1; i >= 0; i--) {
			if (ch == codes[i]) {
				return nums[i];
			}
		}

		return 0;
	}

	private char nextChar(char ch) {
		for (int i = codes.length - 1; i >= 0; i--) {
			if (ch == codes[i]) {
				return codes[i + 1];
			}
		}

		return ch;
	}

	public String convert(int num) {
		if (num < 1 || num > 3999) {
			return "invalid num";
		}

		StringBuffer sb = new StringBuffer();

		while (num > 0) {
			num = handle(sb, num);
			num = handleRepeat(sb, num);
		}

		return sb.toString();
	}

	public int handle(StringBuffer sb, int num) {
		for (int i = nums.length - 1; i >= 0; i--) {
			if (num >= nums[i]) {
				num = num - nums[i];
				sb.append(codes[i]);
				break;
			}
		}

		return num;
	}

	public int handleRepeat(StringBuffer sb, int num) {
		if (sb.length() > 3) {
			char c1 = sb.charAt(sb.length() - 1);
			char c2 = sb.charAt(sb.length() - 2);
			char c3 = sb.charAt(sb.length() - 3);
			char c4 = sb.charAt(sb.length() - 4);

			if (c1 == c2 && c2 == c3 && c3 == c4) {

				if (sb.length() >= 5) {
					char c5 = sb.charAt(sb.length() - 4);

					if (c5 > 0) {
						sb.setLength(sb.length() - 4);

						char nextCh = nextChar(c1);

						sb.append(c1);
						sb.append(nextCh);
					} else {
						sb.setLength(sb.length() - 4);

						char nextCh = nextChar(c1);

						sb.append(c1);
						sb.append(nextCh);
					}
				}
			}

			return num;
		}
		
		return 0;
	}

	public static String Convert(int num) {
		if (num < 1 || num > 3999) {
			return "invalid num";
		}

		Test1 convert = new Test1();
		return convert.convert(num);
	}

	public static void main(String[] args) {
		System.out.println(Convert(399));
	}
}
